/*
 * read.c
 *
 * Asif Shahidullah
 * ECE 275 A.1
 *
 * Code for file operations
 */

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

#include "read.h"

/* Handles opening the files and returning any associated errors */
int
init_files (files_t *file_handler, char *input_file, char *output_file) {
  file_handler->input_file = fopen (input_file, "r");
  if (file_handler->input_file == NULL) {
    fprintf (stderr, "ERRNO: %i: Failed to open input file.\n", errno);
    return -1;
  }
  file_handler->output_file = fopen (output_file, "w");
  if (file_handler->output_file == NULL) {
    fprintf (stderr, "ERRNO: %i: Failed to create output file.\n", errno);
    return -1;
  }

  return 0;
}

/* Responsible for removing additional whitespaces */
int
splice (files_t *file_handler) {
  char c = (char) fgetc (file_handler->input_file);
  while (c != EOF) {
    if (c == 9 || c == 32) {
      while (c == 9 || c == 32 || c == 10)
        c = (char) fgetc (file_handler->input_file);
      fputc (32, file_handler->output_file);
    } 
    fputc (c, file_handler->output_file);
    c = (char) fgetc (file_handler->input_file);
  }

  return 0;
}

/* Close files; code doesn't attempt to abnormally exit here since this is the 
 * second to last function called. */
void
close_files (files_t *file_handler) {
  if ((fclose (file_handler->input_file) || 
      fclose (file_handler->output_file)) != 0)
    fprintf (stderr, "Failed to close files.");
}
